package com.itheima.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import com.itheima.health.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    //依赖注入
    @Reference
    private UserService userService;

    /**
     * 删除用户
     * @param id
     * @return
     */
    @RequestMapping("delete")
    public Result delete(Integer id){
        try {
            //调用Service
            userService.delete(id);
            return new Result(true,MessageConst.DELETE_MEMBER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"该用户为管理人员,不可删除!");
        }
    }

    /**
     * 编辑用户
     * @param user
     * @return
     */
    @RequestMapping("edit")
    public Result edit(@RequestBody User user,Integer[] roleIds){
        try {
            //调用Service
            userService.edit(user,roleIds);
            return new Result(true,MessageConst.EDIT_MEMBER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.EDIT_MEMBER_FAIL);
        }
    }

    /**
     * 编辑角色-- 回显角色项中用户id关联的权限集合
     * @param id
     * @return
     */
    @RequestMapping("findRoleIdsByUserId")
    public Result findRoleIdsByUserId(Integer id){

        try{
            List<Integer> roleList =userService.findRoleIdsByUserId(id);
            return new Result(true, MessageConst.ACTION_SUCCESS,roleList);

        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConst.ACTION_FAIL);

        }
    }


    /**
     * 根据id查询用户,回显
     * @param id
     * @return
     */
    @RequestMapping("findById")
    public Result findById(Integer id){
        try {
            //调用Service中的查询方法
            Map<String,Object> userList = (Map<String, Object>) userService.findById(id);
            //Date birthday = DateUtils.parseString2Date((String) userList.get("birthday"));
            String birthday = DateUtils.parseDate2String((Date) userList.get("birthday"));
            userList.put("birthday",birthday);
            return new Result(true,"查询用户成功",userList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"查询用户失败");
        }
    }

    /**
     * 添加用户
     * 调用Servic中的add方法
     * 返回成功信息
     * 返回失败信息
     * @param user
     * @return
     */
    @RequestMapping("add")
    public Result add(@RequestBody User user,Integer[] roleIds){
        try {
            //调用Service中的方法
            userService.add(user,roleIds);
            return new Result(true,MessageConst.ADD_MEMBER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.ADD_MEMBER_FAIL);
        }
    }

    /**
     * 查询分页数据
     * 1.调用Service获取分页结果数据
     * 2.成功，直接返回有内容的结果
     * 3.失败，返回初始化结果，记录为0，数据为空
     *
     * @param queryPageBean 页面传过来的数据( 当前页, 每条记录数, 查询条件)
     * @return 分页数据( 总记录数, 当前页要显示的10个检查项的集合对象)
     */
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        //日志打印
        log.debug("queryPageBean ===currentPage:{}===pageSize:{}====queryString:{}", queryPageBean.getCurrentPage(), queryPageBean.getPageSize(), queryPageBean.getQueryString());
        try {
            //调用Service获取分页结果数据
            PageResult pageResult = userService.pageQuery(queryPageBean);
            //成功，直接返回有内容的结果
            return pageResult;
        } catch (Exception e) {
            e.printStackTrace();
            //失败，返回初始化结果，记录为0，数据为空
            return new PageResult(0L, null);
        }
    }

    /**
     * 获取用户名
     * @return
     */
    @RequestMapping("/getUsername")
    public Result getUsername(){
        try {
            //从授权框架上下文对象中 获取认证对象
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            //再从 认证对象中 获取授权框架用户对象User
            org.springframework.security.core.userdetails.User user = (org.springframework.security.core.userdetails.User) authentication.getPrincipal();
            //用户对象User 获取 用户名
            String username = user.getUsername();
            //获取成功, 返回成功信息, 并返回用户名
            return new Result(true, MessageConst.ACTION_SUCCESS, username);
        } catch (Exception e) {
            e.printStackTrace();
            //获取失败,返回失败信息
            return new Result(false, MessageConst.ACTION_FAIL);
        }
    }


    /**
     * 登录成功
     * @return
     */
    @RequestMapping("/loginSuccess")
    public Result loginSuccess(){
        return new Result(true,MessageConst.LOGIN_SUCCESS);
    }

    /**
     * 登录失败
     * @return
     */
    @RequestMapping("/loginFail")
    public Result loginFail(){
        return new Result(false,"登录失败");
    }


    @RequestMapping("/login")
    public Result login(String username, String password){
        System.out.println("oms backend====u:"+username+" ,p:"+password);
        if (userService.login(username, password)){
            System.out.println("login ok!!!");
            return new Result(true, MessageConst.ACTION_SUCCESS);
        } else {
            System.out.println("login fail");
            return new Result(false, MessageConst.ACTION_FAIL);
        }
    }
}
